package com.cy.dda.web.comm;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.cy.dda.model.Result;
import com.cy.dda.model.domain.user.UserWechat;
import com.cy.dda.model.dto.wechat.WechatMessageTemplateDTO;
import com.cy.dda.model.enums.wechat.WechatSopce;
import com.cy.dda.service.wechat.WechatService;
import com.cy.dda.web.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信相关api
 *
 * @author: tanyilin
 * @create: 2018年11月20日 下午5:26:25
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
@Api(tags = "微信相关api")
public class WechatController extends BaseController {

	@Autowired
	private WechatService wechatService;
	@Value("${app.home.page}")
    private String appHomePage;
	
	@ApiOperation("公众号验证token")
    @GetMapping("/verify/token")
    public String verifyToken(String echostr) {
        return echostr;
    }
	
	@ApiOperation("获取微信分享签名")
    @GetMapping("/share/signature")
	public Result<Map<String, String>> getShareSignature(String url) {
		String token = wechatService.getAccessToken();
		String ticket = wechatService.getTicket(token);
		Map<String, String> map = wechatService.getShareSignature(token, ticket, url);
		return ok("", map);
	}
	
	@ApiOperation("获取用户授权地址url")
    @GetMapping("/authorize/url")
	public Result<String> getAuthorizeUrl(WechatSopce wechatSopce) {
		Long userId = this.getUser().getUserId();
		String url = wechatService.getAuthorizeUrl(userId, wechatSopce);
		return ok("", url);
	}
	
	@ApiOperation("绑定用户授权回调方法")
    @GetMapping("/bind/callback") 
	public ModelAndView bindCallback(String code, String state) {
		log.info("绑定用户授权回调方法  ======== start");
		UserWechat userWechat = wechatService.bindCallback(code, state);
		wechatService.bindUserWechat(userWechat);
		log.info("绑定用户授权回调方法  ======== end");
		return new ModelAndView("redirect:".concat(appHomePage));
	}
	
	@ApiOperation("发送微信模板消息")
    @GetMapping("/send/message/template")
	public Result sendMessageTemplate() {
		WechatMessageTemplateDTO wechatMessageTemplateDTO = new WechatMessageTemplateDTO();
		Result result = wechatService.sendTemplateMessage(wechatMessageTemplateDTO);
		return result;
	}
	
}
